package com.jet.cashier.dao;

import com.jet.cashier.domain.entity.CashierIgnoreEntity;
import com.jet.cashier.domain.entity.CashierModeEntity;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author dcl
 * @since 2025/4/27 13:40
 */
@Repository
public class CashierModeDao {

    @Resource
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    public int save(CashierModeEntity entity) {
        StringBuilder sb = new StringBuilder();
        sb.append("INSERT INTO m_cashier_mode (")
                .append(" id, merchant_no, store_no, account_id, mobile_mode, pc_mode, create_time, update_time ")
                .append(" ) VALUES ( ")
                .append(" :id, :merchantNo, :storeNo, :accountId, :mobileMode, :pcMode, :createTime, :updateTime ")
                .append(" ) ");

        String sql = sb.toString();
        SqlParameterSource params = new BeanPropertySqlParameterSource(entity);

        return namedParameterJdbcTemplate.update(sql, params);
    }

    public int editPcMode(CashierModeEntity entity) {
        StringBuilder sb = new StringBuilder();
        sb.append("update m_cashier_mode ")
                .append(" set ")
                .append(" pc_mode          = :pcMode, ")
                .append(" update_time   = :updateTime ")
                .append(" where id      = :id AND merchant_no = :merchantNo AND store_no = :storeNo AND account_id = :accountId ");

        String sql = sb.toString();

        SqlParameterSource params = new BeanPropertySqlParameterSource(entity);

        return namedParameterJdbcTemplate.update(sql, params);
    }

    public CashierModeEntity findByAccountId(long merchantNo, long storeNo, String accountId) {
        MapSqlParameterSource params = new MapSqlParameterSource();

        StringBuilder sb = new StringBuilder();
        sb.append("SELECT ")
                .append(" * ")
                .append(" FROM  m_cashier_mode ")
                .append(" WHERE merchant_no = :merchantNo ");

        params.addValue("merchantNo", merchantNo);

        String sql = sb.toString();

        RowMapper<CashierModeEntity> rowMapper = new BeanPropertyRowMapper<>(CashierModeEntity.class);
        List<CashierModeEntity> list = namedParameterJdbcTemplate.query(sql, params, rowMapper);
        return list.stream().findFirst().orElse(null);
    }
}
